package com.huiminpay.merchant.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
@RefreshScope
public class SmsServiceImpl implements ISmsService {
    @Autowired
    RestTemplate restTemplate;
    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.effectiveTime}")
    private String effectiveTime;

    @Override
    public String sendSms(String mobile) {
        // 测试发送短信验证码
        String url = smsUrl+"generate?effectiveTime="+effectiveTime+"&name=sms";

        // 请求体内容
        Map<String,Object> body = new HashMap<>();
        body.put("mobile",mobile);

        // 请求头类型
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

        HttpEntity entity = new HttpEntity(body,headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        System.out.println(JSON.toJSONString(exchange));
        String body1 = exchange.getBody();
        // fastJSON

        JSONObject jsonObject = JSON.parseObject(body1); //
        Integer code = jsonObject.getInteger("code");
        if(code==0){
            // 发送成功

            JSONObject result = jsonObject.getJSONObject("result");
            String key = result.getString("key");
            return key;
        }
        throw new RuntimeException("短信发送失败");
    }

    @Override
    public Boolean checkSmsCode(String code, String key) {
        String url = smsUrl+"verify?name=sms&verificationCode="+code+"&verificationKey="+key;

        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, null, String.class);
        System.out.println(JSON.toJSONString(exchange));
        String body = exchange.getBody();
        /**{
         *   "code": 0,
         *   "msg": "正常",
         *   "result": false
         * }
         */
        JSONObject jsonObject = JSON.parseObject(body);
        Boolean result = jsonObject.getBoolean("result");

        return result;
    }
}
